<template>
  <div class="search-container">
    <!-- 1.顶部栏 -->
    <van-nav-bar title="搜索页" left-arrow @click-left="$router.go(-1)" />
    <!-- 2.搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 3.搜索列表 -->
    <van-cell-group>
      <!-- 点cell传cell内容，注意：showList有span标签，没有span:需要传suggestionList[index] -->
      <van-cell v-for="(item, index) in showList" :key="index" icon="search"
      @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]}})"
      >
        <template #title>
          <span class="custom-title" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
// 导入接口
import {getSuggestion} from './home.js'
export default {
name:'search',
data() {
    return {
        value: '', //搜索内容
        // suggestionList服务器返回的数组（没有颜色）
      suggestionList: [], //推荐词列表
      timeID: null,
    }
},
methods: {
    onSearch(){
        console.log('搜素'+this.value);
        //跳转搜索结果页并传参，点击搜索按钮或者enter键,传当天输入框内容
      this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
     onInput(){
        //   console.log('搜素'+this.value);
     clearTimeout(this.timeID)
     this.timeID=setTimeout(async ()=>{
         console.log('搜素'+this.value);
          // 0.非空判断
        if (this.value=='') {
            this.suggestionList=[]
            return
        }
        // 1.获取推荐词列表
        let res = await getSuggestion(this.value)
        console.log(res);
        // 2.绑定数据
      this.suggestionList = res.data.data.options
     },500)
    }
},
computed:{
    // showList计算属性生成的数值（带颜色）
     showList () {
      //map:遍历数组，根据某种映射规则生成一个新数组
      //这个return返回计算属性值
      return this.suggestionList.map(value => {
        let reg = new RegExp(this.value, 'ig')
        //这个return返回map隐射结果（新数组的元素值）
        return value.replace(
          reg,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
}
}
</script>

<style lang="less">
.search-container {
  .van-nav-bar__content {
    background-color: #0099fa;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
  }
}
</style>
